<template>
  <l-content :app="app" no-padding no-breadcrumb>
    <el-card>
      <el-form :inline="true" size="mini"
               class="border-bottom-dashed"
               :model="searchForm" label-width="100px"
               onkeydown="if(event.keyCode===13){return false;}" @keyup.native.enter="onSearch">
        <div>
          <el-form-item label="申请日期起">
            <el-date-picker
              value-format="yyyy-MM-dd"
              class="w120"
              v-model="searchForm.applyStart"
              type="date"
              placeholder="起始日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="申请日期止">
            <el-date-picker
              value-format="yyyy-MM-dd"
              class="w120"
              v-model="searchForm.applyEnd"
              type="date"
              placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="店铺">
            <el-select class="w120" v-model="searchForm.shop" clearable filterable placeholder="请选择">
              <el-option v-for="item in options.shop" :label="item.shopName" :value="item.shopNo" :key="item.shopNo"/>
            </el-select>
          </el-form-item>
          <el-form-item label="网店出票单号">
            <el-input class="w120" v-model="searchForm.issueBillId" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="PNR">
            <el-input class="w120" v-model="searchForm.pnr" placeholder="支持查原PNR"/>
          </el-form-item>
          <el-form-item label="支付流水号">
            <el-input class="w120" v-model="searchForm.payNo" placeholder="支付流水号"/>
          </el-form-item>
          <el-form-item>
            <el-button :loading="loading" type="primary" @click="onSearch">查询</el-button>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="航班日期起">
            <el-date-picker
              value-format="yyyy-MM-dd"
              class="w120"
              v-model="searchForm.flightStart"
              type="date"
              placeholder="起始日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="航班日期止">
            <el-date-picker
              value-format="yyyy-MM-dd"
              class="w120"
              v-model="searchForm.flightEnd"
              type="date"
              placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="航司" prop="airline">
            <el-select v-model="searchForm.airline" class="w120" clearable placeholder="请选择" filterable>
              <el-option v-for="item in options.airlineOptions" :key="item.key" :label="item.value" :value="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="航班号">
            <el-input class="w120" v-model="searchForm.flight" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="票号">
            <el-input class="w120" v-model="searchForm.ticketNoAll" placeholder="请输入"/>
          </el-form-item>
           <el-form-item label="乘机人">
            <el-input class="w120" v-model="searchForm.passenger" placeholder="请输入"/>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="onAdd">新增</el-button>
          </el-form-item>
           <el-form-item>
            <a :href="exportReport" download class="el-button el-button--mini">导出</a>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="退票单号">
            <el-input class="w120" v-model="searchForm.prid" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="航司退款金额">
            <el-input class="w120" v-model="searchForm.airlineRefund" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="出票渠道">
            <el-select class="w120" v-model="searchForm.issueChannel" clearable placeholder="请选择">
              <el-option v-for="item in options.issueChannel" :label="item.value" :value="item.key" :key="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="平台退票类型">
            <el-select class="w120" v-model="searchForm.refundType" clearable placeholder="请选择">
              <el-option v-for="item in options.platformRefundType" :label="item.value" :value="item.key" :key="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="航司退票类型">
            <el-select class="w120" v-model="searchForm.airlineRefundType" clearable placeholder="请选择">
              <el-option v-for="item in options.refundType" :label="item.value" :value="item.key" :key="item.key"/>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div class="tool-button-box">
        <el-button size="small" plain @click="onChangeStatus('')" :class="(!query.status)?'active':''">
          全部（{{statusCount.ALL}}）
        </el-button>
        <el-button size="small" plain @click="onChangeStatus('TO_CONFIRM')"
                   :class="query.status === 'TO_CONFIRM'?'active':''">
          待确认（{{statusCount.TO_CONFIRM}}）
        </el-button>
        <el-button size="small" plain @click="onChangeStatus('CONFIRMED')"
                   :class="query.status === 'CONFIRMED'?'active':''">
          待取消PNR（{{statusCount.CONFIRMED}}）
        </el-button>
        <el-button size="small" plain @click="onChangeStatus('TO_HANDLE')"
                   :class="{'active': query.status === 'TO_HANDLE'}">
          待人工处理（<span :class="{'font-red': statusCount.TO_HANDLE > 0}">{{statusCount.TO_HANDLE}}</span>）
        </el-button>
        <el-button size="small" plain @click="onChangeStatus('TO_SUBMIT_AIRLINE')"
                   :class="query.status === 'TO_SUBMIT_AIRLINE'?'active':''">
          待提交退票（{{statusCount.TO_SUBMIT_AIRLINE}}）
        </el-button>
        <el-button size="small" plain @click="onChangeStatus('TO_AIRLINE_AUDIT')"
                   :class="query.status === 'TO_AIRLINE_AUDIT'?'active':''">
          待航司审核（{{statusCount.TO_AIRLINE_AUDIT}}）
        </el-button>
        <el-button size="small" plain @click="onChangeStatus('TO_AIRLINE_REFUND')"
                   :class="query.status === 'TO_AIRLINE_REFUND'?'active':''">
          待航司退款（{{statusCount.TO_AIRLINE_REFUND}}）
        </el-button>
        <el-button size="small" plain @click="onChangeStatus('AIRLINE_REFUNDED')"
                   :class="query.status === 'AIRLINE_REFUNDED'?'active':''">
          完成退票（{{statusCount.AIRLINE_REFUNDED}}）
        </el-button>
        <el-button size="small" plain @click="onChangeStatus('REJECTED')"
                   :class="query.status === 'REJECTED'?'active':''">
          拒绝（{{statusCount.REJECTED}}）
        </el-button>
      </div>
      <c-page-table
        show-summary
        stripe
        :data="tableData"
        :max-height="tableHeight"
        @select-page="onSelectPage"
        @sort-change="onSortChange"
        @row-dblclick="row => onDetail(row)"
        :summary-method="tableSummary"
        :loading="loading">
        <el-table-column
          fixed
          label="操作"
          width="80">
          <template slot-scope="scope">
            <a href="javascript:void(0)" @click="onDetail(scope.row)" title="详情">详</a>
            <a href="javascript:void(0)" @click="onHandle(scope.row)" title="处理" v-if="showHandle(scope.row)"><span class="mark-handle" >处</span></a>
            <!--a href="javascript:void(0)" @click="onDelete(scope.row)" title="删除" v-if="showDelete(scope.row)">删</a-->
          </template>
        </el-table-column>
        <el-table-column
          label="退票单信息"
        >
          <el-table-column
            prop="prid"
            label="退票单号"
            width="80">
            <template slot-scope="scope">
             {{scope.row.prid}}
            </template>
          </el-table-column>
          <el-table-column
            prop="shopName"
            label="网店"
            min-width="75">
          </el-table-column>
          <el-table-column
            label="申请退票日期"
            width="135">
            <template slot-scope="scope">
              <div>{{scope.row.rtTime | datetimeShortFormat1}}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="pnr"
            label="PNR"
            min-width="60">
          </el-table-column>
          <el-table-column
            label="航班日期"
            width="135">
            <template slot-scope="scope">
              {{scope.row.takeOffTime | datetimeShortFormat1}}
            </template>
          </el-table-column>
          <el-table-column
            label="航程"
            prop="ports"
            min-width="75">
          </el-table-column>
          <el-table-column
            prop="flight"
            label="航班"
            min-width="60">
          </el-table-column>
          <el-table-column
            prop="subClass"
            label="舱"
            min-width="25">
          </el-table-column>
          <el-table-column
            prop="passengerInfoStr"
            label="乘客"
            min-width="70">
          </el-table-column>
        </el-table-column>

        <el-table-column
          label="平台退票">
          <el-table-column
            prop="refundType"
            label="类型"
            width="70">
          </el-table-column>
          <el-table-column
            prop="cost"
            label="销售价"
            width="70">
          </el-table-column>
          <el-table-column
            prop="taxFee"
            label="税费"
            width="70">
            <template slot-scope="scope">
              {{(Number(scope.row.oilFee || 0) + Number(scope.row.tax || 0)) | money}}
            </template>
          </el-table-column>
          <el-table-column
            prop="subtotal"
            label="小计"
            width="70">
            <template slot-scope="scope">
              {{(Number(scope.row.oilFee || 0) + Number(scope.row.tax || 0) + Number(scope.row.cost || 0)) | money}}
            </template>
          </el-table-column>
          <el-table-column
            prop="platformRefundFee"
            label="退票费"
            width="70">
          </el-table-column>
          <el-table-column
            prop="platformRefund"
            label="平台退款"
            width="70">
          </el-table-column>
          <el-table-column
            label="最晚取消PNR时间"
            width="120">
            <template slot-scope="scope">
              <div>{{scope.row.latestCancelPnrTime | datetimeShortFormat1}}</div>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column
          label="航司退票">
          <el-table-column
            prop="airlineRefund"
            label="航司退款"
            width="70">
          </el-table-column>
          <el-table-column
            prop="refundProfit"
            label="利润"
            width="60">
          </el-table-column>
          <el-table-column
            prop="airlineRefundTypeName"
            label="类型"
            title="提交航司退票类型"
            width="65">
          </el-table-column>
          <!--el-table-column
            prop="submituser"
            label="提交退票人"
            width="70">
          </el-table-column-->
          <el-table-column
            label="提交时间"
            title="提交航司退票时间"
            width="115">
            <template slot-scope="scope">
              <div>{{scope.row.submitRefundTime | datetimeShortFormat1}}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="remarks"
            label="备注"
            min-width="100">
          </el-table-column>
        </el-table-column>
      </c-page-table>
    </el-card>

    <component :is="dialog.tag" :data="dialog.data" @ok="refreshPage"
               @close="dialog.tag = ''" />
  </l-content>
</template>

<script>
import CancelPnrDialog from './comps/OrderRefundList/CancelPnrDialog'
import tabManager from '@/eventBus/tabManager'
import Tab from '@/classes/Tab'
import ui from '@mixins/ui'

export default {
  mixins: [ui],
  name: 'OrderIssueList',
  components: {
    CancelPnrDialog
  },
  props: {
    app: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  filters: {
    takeOffTimeFilter (val) {
      const now = new Date()
      if (val < new Date(now.getFullYear(), now.getMonth(), now.getDate() + 2)) {
        return 'bg-red'
      }
    }
  },
  data () {
    const now = new Date()
    const nowStr = now.format('yyyy-MM-dd')
    const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
    const yesterdayStr = yesterday.format('yyyy-MM-dd')
    const searchForm = {
      applyStart: yesterdayStr,
      applyEnd: nowStr,
      flightStart: null,
      flightEnd: null,
      pnr: null,
      passenger: null,
      issueBillId: null,
      localOrderId: null,
      prid: null,
      ticketNo: null,
      refundType: null,
      shop: null,
      issueChannel: null,
      status: 'TO_CONFIRM',
      airlineRefundType: null,
      airline: null,
      payNo: null,
      airlineRefund: null
    }
    const query = Object.assign({
      page: 1,
      pageSize: 50
    }, searchForm)
    return {
      now: now,
      timer: null,
      loading: false,
      options: {
        issueChannel: [],
        shop: [],
        refundType: [],
        airlineOptions: [],
        platformRefundType: []
      },
      searchForm: searchForm,
      query: query,
      tableData: {
        /* 表格数据固定写法 */
        records: 0,
        page: 1,
        rows: []
      },
      statusCount: {
        ALL: 0,
        TO_CONFIRM: 0,
        REJECTED: 0,
        CONFIRMED: 0,
        TO_HANDLE: 0,
        TO_SUBMIT_AIRLINE: 0,
        TO_AIRLINE_AUDIT: 0,
        TO_AIRLINE_REFUND: 0,
        AIRLINE_REFUNDED: 0
      },
      dialog: {
        tag: '',
        data: {}
      }
    }
  },
  computed: {
    exportReport () {
      return this.$service.airRefund.exportReport(this.query)
    },
    tableHeight () {
      const tableHeight = this.ui.screenHeight - 400
      return tableHeight < 400 ? 400 : tableHeight
    }
  },
  created () {
    this.$dateUtils.getNow().then(now => {
      this.now = now
    })
    this.onSearch()
    this.loadOptions()
    // 10秒更新一次数字
    this.timer = setInterval(this.loadCount.bind(this), 10000)
  },
  beforeDestroy () {
    clearInterval(this.timer)
  },
  methods: {
    loadOptions () {
      this.$service.options.getIssueChannel().then(res => {
        this.options.issueChannel = res.data
      })
      this.$service.order.queryAirOnlineShopList().then(res => {
        this.options.shop = res.data
      })
      this.$service.options.getRefundType().then(res => {
        this.options.refundType = res.data || []
        this.options.refundType.splice(1, 0, {'key': 'NOT_VOLUNTARY', 'value': '非自愿'})
      })
      this.$service.options.getAirLineOption().then(res => {
        this.options.airlineOptions = res.data
      })
      this.options.platformRefundType = [
        {'key': '自愿', 'value': '自愿'},
        {'key': '非自愿', 'value': '非自愿'}
      ]
    },
    tableSummary (param) {
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '汇总'
          return
        }
        if (index < 12 || index > 18) {
          sums[index] = ''
          return
        }
        if (column.property === 'taxFee') {
          const values = data.map(item => Number(item['tax'] || 0) + Number(item['oilFee'] || 0))
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = this.$options.filters.money(sum)
          return
        } else if (column.property === 'subtotal') {
          const values = data.map(item => Number(item['tax'] || 0) + Number(item['oilFee'] || 0) + Number(item['cost'] || 0))
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = this.$options.filters.money(sum)
          return
        }
        const values = data.map(item => Number(item[column.property] || 0))
        const sum = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        sums[index] = this.$options.filters.money(sum)
      })
      return sums
    },
    onChangeStatus (v) {
      this.searchForm.status = v
      this.onSearch()
    },
    onSearch () {
      // 把searchForm里面的值覆盖到paramForm里面去
      Object.assign(this.query, this.searchForm)
      this.query.page = 1
      this.refreshPage()
    },
    onSelectPage (page, size) {
      this.query.page = page
      this.query.pageSize = size
      this.refreshPage()
    },
    onSortChange ({sidx, sord}) {
      // 排序设置
      this.query.sidx = sidx
      this.query.sord = sord
      this.refreshPage()
    },
    loadCount () {
      this.$service.airRefund.countByStatus(this.query).then(res => {
        this.statusCount = {
          ALL: 0,
          TO_CONFIRM: 0,
          REJECTED: 0,
          CONFIRMED: 0,
          TO_HANDLE: 0,
          TO_SUBMIT_AIRLINE: 0,
          TO_AIRLINE_AUDIT: 0,
          TO_AIRLINE_REFUND: 0,
          AIRLINE_REFUNDED: 0
        };
        (res.data || []).forEach(i => {
          this.statusCount[i.status] = i.count
          this.statusCount.ALL += i.count
        })
      })
    },
    // 为了锁单时转圈圈
    refreshPage (loading = true) {
      this.loading = loading
      this.$service.airRefund.queryOrderPage(this.query).then(res => {
        this.tableData = res.data
      }).finally(() => {
        this.loading = false
      })
      this.loadCount()
    },
    firstPage () {
      this.query.page = 1
      this.refreshPage()
    },
    onDetail (row) {
      let name = '退票单'
      if (row.prid != null) {
        name = '退票单-' + row.prid
      }
      tabManager.addTab(new Tab({
        key: 'airOrderManage.orderRefundDetail',
        name: name,
        extra: {refundId: row.id}
      }))
    },
    onAdd () {
      tabManager.addTab(new Tab({
        key: 'airOrderManage.orderRefundAdd',
        name: '新增退票单'
      }))
    },
    showHandle (row) {
      return row.status === 'TO_HANDLE' || (row.status === 'CONFIRMED' && (new Date(row.latestCancelPnrTime).getTime() - this.now.getTime()) <= 30 * 60 * 1000)
    },
    onHandle (row) {
      this.dialog.data = {
        refundId: row.id,
        officeNo: row.issueOfficeNo,
        pnr: row.pnr,
        latestCancelPnrTime: row.latestCancelPnrTime
      }
      this.dialog.tag = 'CancelPnrDialog'
    },
    showDelete (row) {
      return row.status === 'TO_CONFIRM' || row.status === 'CONFIRMED' || row.status === 'TO_HANDLE' || row.status === 'TO_SUBMIT_AIRLINE'
    },
    onDelete (row) {
      this.$confirm('是否删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$service.airRefund.delete({id: row.id}).then(res => {
          this.refreshPage()
        })
      })
    }
  }
}
</script>

<style></style>
